﻿using System;
using System.Text;

namespace Sencha.Serialization
{
	public sealed class JsonStringBuilderReader : JsonReaderBase
	{
		private StringBuilder m_jsonString;
		private int m_position;

		public JsonStringBuilderReader(StringBuilder str)
			: this(str, new AdHocSerializer(), DefaultBufferSize)
		{

		}
		public JsonStringBuilderReader(StringBuilder str, int bufferSize = DefaultBufferSize)
			: this(str, new AdHocSerializer(), bufferSize)
		{

		}
		public JsonStringBuilderReader(StringBuilder str, ISerializationContext context, int bufferSize = DefaultBufferSize)
			: base(context, bufferSize)
		{
			if (str == null)
				throw new ArgumentNullException("str");
			System.Diagnostics.Contracts.Contract.EndContractBlock();

			m_jsonString = str;
			m_position = 0;
		}

		protected override int FillBuffer(char[] buffer, int index)
		{
			if (buffer == null)
				throw new ArgumentNullException("buffer");
			if (index < 0 || index >= buffer.Length)
				throw new ArgumentOutOfRangeException("index");
			System.Diagnostics.Contracts.Contract.EndContractBlock();

			var block = Math.Min(m_jsonString.Length - m_position, buffer.Length - index);
			if (block <= 0)
				return index;

			m_jsonString.CopyTo(m_position, buffer, index, block);

			m_position += block;

			return index + block;
		}
	}
}
